<?php
include_once 'ctype/base/baseField.php';

/*
 * data: array(
 * 	'path' 			=> '....',
 * 	'other_info'	=> ...
 * )
 */

class Upload extends BaseField{
	
	var $template = "ctype/views/fields/upload.php";
	
	var $properties = array(
		"title"							=> "Texto",
		"description" 					=> "Descripción del campo texto",
		"upload_automatic"				=> "false",
		"upload_path"					=> "contents/{year}/{month}/",
		"upload_tmp_path"				=> "contents/tmp/",
		"multiple"						=> FALSE
	
		//"upload_allow_filetypes"		=> "jpg|png|jpeg|gif",
		//"upload_allow_filetypes_msg"	=> "Solo JPG, PNG y GIF son validos",
	);
	
	
	function Upload(){
		parent::BaseField();
		$this->addStatic("javascript", "ajaxFileUpload.js");
		
		$this->properties["upload_path"] = str_replace("{year}", date('Y'), $this->properties["upload_path"]);
		$this->properties["upload_path"] = str_replace("{month}", date('m'), $this->properties["upload_path"]);
		$this->properties["upload_path"] = str_replace("{day}", date('d'), $this->properties["upload_path"]);
		
		if(!file_exists($this->properties['upload_tmp_path'])){
			mkdir($this->properties['upload_tmp_path'], 0777, true);
		}
		
		$this->clearTmpFolder();
	}
	
	function view($node = NULL, $data = NULL){
		$value = $data;
		
		if($data != NULL){
			if(isset($data['path'])){
				$value = $data['path'];
			} else{
				$value = array();
				foreach($data as $d){
					if(isset($d['path'])){
						array_push($value, $d['path']);
					}
				}
			}
		}
		
		$name = $this->formName;
		$properties = $this->properties;
		$required = $this->required;
		
		ob_start();
		eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($this->template, TRUE))));
		$view = ob_get_contents();
		@ob_end_clean();
		
		return $view;
	}
	
	function save($node = NULL, $data = NULL){
		
		$files = $this->ci->input->post($this->formName);
		
		//Mejora para no redimensionar las imagenes innecesariamente
		//Eliminamos los files antes de tratar los nuevos
		$this->delete_old_data($data, $files);
		
		//Recorrer $files y si empieza a por $upload_tmp_path, moverlo al nuevo y eliminar el antiguo
		$newData = array();
		
		if($files != NULL){
			log_message("debug", "Save field: '{$this->name}' type: 'Upload' data: '".print_r($files, TRUE)."'");
			
			if(!file_exists($this->properties['upload_path'])){
				log_message("debug", "Creamos el directorio de subida: '{$this->properties['upload_path']}'");
				
				mkdir($this->properties['upload_path'], 0777, true);
			}
				
			foreach($files as $file){
				if($file != ""){
					if( strpos($file, $this->properties['upload_tmp_path']) === 0){ //Si comienza con /tmp...
						
						
						$path = $this->properties['upload_path'];
						$filename = $this->getFileName($path, basename($file));
					
						$newFile = $path . $filename;
					
						log_message("debug", "Movemos el fichero de: '{$file}' a: '{$newFile}'");
						//Asociar a la tabla de archivos				
						if(copy($file, $newFile)){
							unlink($file);
						} else{
							log_message("error", "Error copiando el fichero de: '{$file}' a: '{$newFile}'");
						}
						
						$newFileData = $this->createFileData($newFile);
						log_message("debug", "Informacion de upload: '".print_r($newFileData, TRUE)."'");
						
						if($newFileData != NULL){
							if(isset($this->properties['multiple']) && $this->properties['multiple'] === FALSE){
								$newData = $newFileData;
							} else{
								array_push($newData, $newFileData);
							}
						} else{
							log_message('error', "El fichero '$newFile' no ha devuelto informacion.. puede que no exista");
						}
						
					} else{
						log_message("debug", "El fichero ya estaba subido: '{$file}'");
						$newFileData = $this->createFileData($file);
						log_message("debug", "Informacion de upload: '".print_r($newFileData, TRUE)."'");
						
						if($newFileData != NULL){
							if(isset($this->properties['multiple']) && $this->properties['multiple'] === FALSE){
								$newData = $newFileData;
							} else{
								array_push($newData, $newFileData);
							}
						} else{
							log_message('error', "El fichero '$file' no ha devuelto informacion.. puede que no exista");
						}
					}
				}
			}
		}
		
		return $newData;
	}
	
	function delete_old_data($old_data=NULL, $files=array()){
		if($old_data != NULL){
			if(isset($old_data['path'])){
				if(!in_array($old_data['path'], $files)){
					$this->delete_data_file($old_data);
				}
			} else{
				foreach($old_data as $old_data_item){
					$this->delete_old_data($old_data_item, $files);
				}
			}
		}
	}
	
	
	function delete_data_file($data){
		unlink($data['path']);
	}
	
	function createFileData ($filePath){
		if(file_exists($filePath)){
			$data = array();
			$data['path'] = $filePath;
			$data['size'] = filesize($filePath);
			$data['type'] = filetype($filePath);
			
			return $data;
		}
		
		return NULL;
	}
	
	function delete($node = NULL, $data = NULL){
		if($data != NULL){
			if(!isset($data['path'])){
				foreach($data as $data_item){
					$this->delete_data_file($data_item);
				}
			} else{
				$this->delete_data_file($data);
			}
		}
		
		return TRUE;
	}
	
	function getFileName($path, $filename){
		
		if ( ! file_exists($path.$filename)){
			return $filename;
		}
		
		$pathinfo = pathinfo($filename);		
		
		$new_filename = '';
		for ($i = 1; $i < 100; $i++){			
			if ( ! file_exists($path.$pathinfo['filename'].$i.".".$pathinfo['extension']))
			{
				$new_filename = $pathinfo['filename'].$i.".".$pathinfo['extension'];
				break;
			}
		}

		if ($new_filename == ''){
			//$this->set_error('upload_bad_filename');
			return FALSE;
		} else{
			return $new_filename;
		}
	}
	
	function clearTmpFolder(){
		//dias*horas*minutos*segundos
		$maxOld = 1*24*60*60;
		
		$dir = $this->properties["upload_tmp_path"];
		if ($handle = opendir($dir)) {
			while (false !== ($file = readdir($handle))) {
		        if(!is_dir($dir . $file)){
		        	$time = filemtime($dir . $file);
		        	$now = time();
		        	
		        	$timedif = $now-$time;
		        	//Si supera el tiempo estipulado, limpiamos el file
		        	if($timedif>$maxOld){
		        		if(file_exists($dir . $file)){
		        			unlink($dir . $file);
		        		}
		        	}
		        }
		    }
		}
	}
	
}
?>